<!--
 * @LastEditors: Yang.Zzz
 * @LastEditTime: 2024-05-17 15:09:39
-->
<script setup>
import TaskList from './taskList.vue'
import { onMounted, reactive, ref ,computed , watch  } from "vue";
import { useStore } from 'vuex'
import { useRoute, useRouter } from "vue-router";
import instance  from '../utils/api'
import { user_mock}   from '../utils/mock'
import { ElMessage } from 'element-plus'
   const form = reactive({
        phoneNumber: '',
        verificationCode: '',
        email: '',
        password: '',
        confirmPassword: '',
    })

    const emailForm = reactive({
        email: '',
        verificationCode: '',
        password: '',
        confirmPassword: '',
    })


    const handleSureNumberInputValue = (key,val) => {
        let _form;
        _form = tabSelectItem.value === 'phone' ? form : emailForm 
        _form[key] = val.replace(/[^\d]/g, ''); 
    }

    watch(  
        () => form.phoneNumber, // 依赖项  
        (newVal) => { // 回调函数  
            handleSureNumberInputValue('phoneNumber',newVal)
        }
    );

    const tabSelectItem = ref(undefined) // 选中的注册方式
    
    onMounted(() => {
        tabSelectItem.value = 'phone' // 默认为手机号注册
        getUserInfo()
    })

    const getUserInfo = async() => {
        const params = {
            type: 'userlogin'
        }
        try {

        } catch (error) {
            console.log("🚀 ~ getUserInfo ~ error:", error)
        }
    }


    const phoneRuleFormRef = ref(null)
    const emailRuleFormRef = ref(null)


    // 通用的 输入 处理表单验证方法 formEl ref 实例；value 值; key 字段值
    const handleFormInputValidate = (formEl,value,key) => {
        if (!formEl) return;
        if(value === '' ||  value === undefined || value === null) {
            // formEl.validateField(key) 会报错 而formEl.validateField(key) 返回的是一个 promise 对象
            formEl.validateField(key).then(res=>{}).catch(err=>{});
        }else {
            formEl.clearValidate(key)
        }
    }

    const validatephone = (rule, value, callback) => {
        if (!/^[0-9]{5,}$/.test(value)) {
            callback(new Error('请输入正确的手机号！'))
        } else {
            callback()
        }
    }

    const validateEmail = (rule, value, callback) => {
        if (!/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(value)) {
            // if (!/^([a-zA-Z0-9_-]{1,16})@([a-zA-Z0-9]{1,9})(\.[a-zA-Z0-9]{1,9}){0,3}(\.(?:com|net|org|edu|gov|mil|cn|us)){1,4}$/.test(value)) {
            callback(new Error('请输入正确的手机号！'))
        } else {
            callback()
        }
    }

    // 表单验证规则
    const phoneRules = reactive({
        phoneNumber: [
            {required: true, message: '请输入手机号', trigger: 'blur'},
            {validator: validatephone,trigger: 'blur'}
        ],
        verificationCode: [
            {required: true, message: '请输入验证码', trigger: 'blur'},
        ],
        email: [{required: true,message: '请输入手机号',trigger: 'blur'},
                {validator: validateEmail,trigger: 'blur'}
        ],
        password: [{required: true,message: '请输入密码',trigger: 'blur' }]
    })


    /* 点击注册按钮 */
    const isSubmitRequest = ref(false) 
    const store = useStore() 
    const router = useRouter()
    const handleClickSubmitButton = () => {
        if(isSubmitRequest.value === true) {
            return;
        }
        
        const formEl = tabSelectItem.value === 'phone' ? phoneRuleFormRef.value : emailRuleFormRef.value
       
        if(!formEl) return;
        formEl.validate(async(valid) => {
            if (valid) {
                isSubmitRequest.value = true
                const result = await new Promise(resolve => {
                    let status = 'error'
                    const activeAccont = user_mock.find((option) => option.phoneNumber === form.phoneNumber)
                    if(activeAccont && activeAccont.password === form.password) {
                        status = 'success'
                        store.dispatch('user/setUserInfo', activeAccont) 
                    }
                    setTimeout(() => { 
                        if(status === 'success') {
                            resolve({
                                status: 200
                            });  
                        }else {
                            resolve({
                                status: 400
                            });  
                        }
                    }, 1500);  
                })
                isSubmitRequest.value = false
                if(result.status === 200) {
                    ElMessage({
                        message: '登录成功！',
                        type: 'success',
                        plain: true,
                    })
                    router.push('/webapp/tasks/all') 
                }else {
                    ElMessage({
                        message: '登录失败！',
                        type: 'error',
                        plain: true,
                    })
                }
            } 
        })
    }
</script>

<template>
    <div class="layout-wrapper layout-wrapper_login">
            <div class="layout-content">
                <div class="layout-left">
                    <div class="layout-header">
                        <a href="/" class="layout-header-logo"></a>
                    </div>
                    <div class="layout-introduce-content">
                        <h1 class="layout-introduce__title">
                            ToDoList
                        </h1>
                        <p class="layout-introduce__desc">
                            个人任务管理工具
                        </p>
                        <p class="layout-introduce__copyright">
                            版权所有© 重庆大学城市科技学院 李劲林
                        </p>
                    </div>
                </div>
                <div class="layout-right">
                    <div class="layout-form">
                        <div class="layout-form-title">
                            登录
                        </div>
                        <div class="layout-form-tabs mt-16 fboxYcenter">
                            <!-- <div class="form-tab__item" @click="tabSelectItem = 'email'" :class="{'is-active': tabSelectItem === 'email'}">
                                手机号登录
                            </div> -->
                            <div class="form-tab__item" @click="tabSelectItem = 'phone'" :class="{'is-active': tabSelectItem === 'phone'}" >
                                手机号登录
                            </div>
                        </div>
                        <div class="layout-form-content">
                            <el-form v-show="tabSelectItem === 'phone'" @keyup.enter="handleClickSubmitButton" :class="{'el-form--active': tabSelectItem === 'phone'}" :model="form" ref="phoneRuleFormRef" :rules="phoneRules">
                                <el-form-item autocomplete="off"  prop="phoneNumber">
                                    <el-input
                                    @input="handleFormInputValidate(phoneRuleFormRef,form.phoneNumber,'phoneNumber')"
                                    v-model="form.phoneNumber"
                                    placeholder="手机号"
                                    class="input-with-select"
                                    clearable
                                    >
                                    </el-input>
                                </el-form-item>
                                
                                <el-form-item autocomplete="off" prop="password">
                                    <el-input type="password" @input="handleFormInputValidate(phoneRuleFormRef,form.password,'password')"
                                        placeholder="登录密码" v-model="form.password" clearable show-password>
                                    </el-input>
                                </el-form-item>
                            </el-form>
                            <el-form v-show="tabSelectItem === 'email'" @keyup.enter="handleClickSubmitButton" :class="{'el-form--active': tabSelectItem === 'email'}" :model="emailForm" ref="emailRuleFormRef" :rules="phoneRules">
                                <el-form-item autocomplete="off" prop="email">
                                    <el-input @input="handleFormInputValidate(emailRuleFormRef,emailForm.email,'email')" placeholder="手机号" v-model="emailForm.email" clearable></el-input>
                                </el-form-item>

                                <el-form-item autocomplete="off" prop="password">
                                    <el-input  type="password" @input="handleFormInputValidate(emailRuleFormRef,emailForm.password,'password')"
                                    placeholder="登录密码" v-model="emailForm.password" clearable show-password>
                                    </el-input>
                                </el-form-item>
                            </el-form>
                            
                            <div id="tncodeaccess_str" style="display: none;"></div>
						    <div class="tncode" style="display: none;text-align: center;width: 100%;"></div>
                        </div>
                        <div class="layout-form-button_wrap mt-16">
                            <div @click="handleClickSubmitButton" :class="{'tpm-btn__loadding': isSubmitRequest }" class="tpm-btn tpm-btn--primary w100">
                                登录
                            </div>
                        </div>
                        <div class="layout-form-goto layout-form-goto__login">
                            <div class="form-goto-register">
                                还没账号？
                                <router-link class="mainColor" to="/register">立即注册</router-link>  
                                <!-- <a href="./register.shtml" target="_self" class="mainColor">立即注册</a> -->
                            </div>
                            <router-link class="form-goto-forgetPwd" to="/findPass">忘记密码</router-link>  
                        </div>
                    </div>
                </div>
            </div>
       </div>

</template>

<style scoped>
.layout-wrapper {
    height: 100vh;
    min-width: 1300px;
    background: linear-gradient(to right, #F6F9FF 50%, #006eff 50%);
}
.layout-wrapper .layout-content {
    max-width: 1920px;
    margin: auto;
    display: flex;
    height: 100%;
    position: relative;
}

.layout-wrapper .layout-content .layout-left {
    position: relative;
    flex: 1;
    background: #F6F9FF;
}

.layout-wrapper .layout-content .layout-right {
    flex: 0 0 27.81%;
    position: relative;
    background: #006eff;
}


.layout-wrapper .layout-form {
    position: absolute;
    top: 50%;
    left: -50%;
    transform: translate(50px,-50%);
    width: 400px;
    box-sizing: border-box;
    padding: 48px 40px;
    background: #FFFFFF;
    box-shadow: 0px 0px 24px 0px rgba(34,28,25,0.1);
    border-radius: 8px;
}

.layout-header {
    position: absolute;
    height: 76px;
    left: 0;
    top: 0;
    width: 100%;
}

.layout-header .layout-header-logo {
    position: absolute;
    top: 0;
    left: 32px;
    bottom: 0;
    display: block;
    width: 45px;
    height: 45px;
    margin: auto 0;
    overflow: hidden;
    background: url(../assets/img/logo.jpg) center no-repeat;
    background-size: 100%;
}

.layout-introduce-content {
    height: 490px;
    position: absolute;
    top: 50%;
    transform: translateY(calc(-50% + 120px));
    right: 0px;
    margin-right: 35%;
}

.layout-introduce-content  .layout-introduce__title {
    height: 58px;
    font-size: 48px;
    font-weight: bold;
    color: var(--titleColor);
    line-height: 56px;
}

.layout-introduce-content .layout-introduce__desc {
    font-family: 'AlimamaShuHeiTi-Bold';
    font-size: 48px;
    color: var(--titleColor);
    line-height: 56px;
    margin-top: 3px;
}

.layout-introduce-content .layout-introduce__copyright {
    margin-top: 140px;
    font-size: 14px;
    font-weight: 600;
    color: #4C5B76;
    line-height: 16px;
}

.layout-form .layout-form-title  {
    font-size: 24px;
    font-weight: 600;
    color: #020814;
    line-height: 28px;
}

.layout-form-tabs .form-tab__item {
    font-size: 16px;
    color: #020814;
    position: relative;
    cursor: pointer;
}

.layout-form-tabs .form-tab__item + .form-tab__item {
    margin-left: 40px;
}


.layout-form-tabs .form-tab__item.is-active {
    color: #006eff;
    font-weight: 600;
}

.layout-form-tabs .form-tab__item.is-active::after {
    content: '';
    display: block;
    position: absolute;
    left: 50%;
    bottom: -8px;
    transform: translateX(-50%);
    width: 0px;
    height: 4px;
    background: #006eff;
    border-radius: 8px;
    animation: activeTabItem 0.3s ease-in 1 0s;
	animation-fill-mode: forwards;
}


@keyframes activeTabItem {
    0% {
        width: 0px;
    }

    100% {
        width: 32px;
    }
}

.layout-form .layout-form-content {
    margin-top: 30px;
}

.layout-form .layout-form-tabs {
    line-height: 22px;
}

.layout-form .el-input .el-input__inner {
    color: #020814;
    /* 加上上下共 2px 的边框高度就是 设计稿 40px 的高度 */
    height: 38px; 
}

.el-form-item .tpm-btn {
    width: 152px;
    flex:  0 0 152px;
    height: 40px;
    line-height: 40px;
}

.tpm-btn.tpm-btn__sendVCode:not(.noclick) {
    border: 1px solid #DCE2EB;
    color: #020814;
    background: transparent;
    box-shadow: none;
    border-radius: 4px;
}

.tpm-btn.tpm-btn__sendVCode:not(.noclick):hover {
    border-color: var(--mainColor);
    color: var(--mainColor);
}

.tpm-btn.noclick {
    cursor: not-allowed;
}

.layout-form__check a:hover , .layout-form-goto a:hover {
    text-decoration: underline;
}

.layout-form__check .el-checkbox__label,.layout-form__check .el-checkbox__input.is-checked+.el-checkbox__label  {
    color: #41464F;
}

.layout-wrapper_login .layout-form-button_wrap {
    margin-top: 60px;
}

.layout-form-button_wrap .tpm-btn {
    height: 42px;
    line-height: 42px;
    border-radius: 20px;
}

.layout-form-button_wrap .tpm-btn.tpm-btn__loadding {
    opacity: 0.45;
    cursor: default;
}

.layout-form-goto {
    margin-top: 24px;
    text-align: center;
    font-size: 14px;
    line-height: 20px;
}

.layout-form-goto.layout-form-goto__login {
    display: flex;
    justify-content: space-between;
    align-items: center;
    line-height: 20px;
}

.form-goto-register {
    color: #A5B1C7;
}

.form-goto-forgetPwd {
    font-size: 14px;
    font-weight: 600;
    color: #020814;
}

.layout-form-goto.layout-form-goto__login .form-goto-forgetPwd:hover {
    text-decoration: none;
}

.v-enter-from {
    transform: translateX(-40px);
}

.v-enter-active{
    transition: transform 0.3s ease-in;
}

.v-enter-to {
    transform: translateX(0px);
}


.el-form--active {
    animation: fadeToleft 0.3s ease-out 1 0s;
	animation-fill-mode: forwards;
}

.layout-form-content .el-input__suffix .el-input__icon{
    color: #333;
}

@keyframes fadeToleft {
    0% {
        transform: translateX(-20px);
        opacity: 0;
    }

    100% {
        transform: translateX(0px);
        opacity: 1;
    }
}

@media screen and (max-width: 1400px) {
    .layout-wrapper .layout-form {
        transform: translate(0px,-50%);
    }
}

</style>
